import { h, ref, Ref, computed, ComputedRef, watch } from 'vue'
import {
  updateDoorThemeColour,
  updateDoorTypeFieldList,
  updateDoorTypeFieldListDraft
} from '@src/api/PortalApi'
import DoorType, { DoorTypeNav } from '@model/entity/DoorType'
import { isEmpty } from '@src/util/type'
import { PortalTabbarEnum, ITabbarsFields, IPortalFields } from '@model/types/PortalConfig'
import { Message, MessageBox } from 'element-ui';
import * as FormUtil from '@src/mform/util'
import _ from 'lodash'
import i18n from '@src/locales';
/* util */
import { isShowLinkCShop, getVersionControlMapByWindow } from '@shb-lib/version'
import { getThemeColor } from "@src/util/business/color"

const _versionControlMap = getVersionControlMapByWindow()

// 自助门户顶部导航栏
export function useConfigNav() {
  const navBarList = [
    { label: i18n.t('portal.portalConfig'), index: 1 },
    { label: i18n.t('portal.portalStyle'), index: 2 },
  ]

  const navIndex = ref<number>(1)

  const handleNavBarClick = (index: number) => {
    navIndex.value = index
  }

  return [navIndex, navBarList, handleNavBarClick];
}

// 自助门户风格配色
export function useConfigStyle() {
  const colorList = ref([{
    label: i18n.t('portal.orange'),
    value: 1,
    color: '#FF7100,#FFFFFF',
  }, {
    label: i18n.t('portal.blue'),
    value: 2,
    color: '#096DD9,#FFFFFF',
  }, {
    label: i18n.t('portal.green'),
    value: 3,
    color: `${getThemeColor()},#FFFFFF`,
  }, {
    label: i18n.t('portal.customConfiguration'),
    value: 4,
    color: '#000000,#FFFFFF',
  }])

  let checkedColor = ref<string>('')
  let backupColor = ref<string>('')

  let customColor = ref<null | string>(null);

  const styleColor = computed(() => {
    return checkedColor.value.match(/(\S*)\,/)?.[1] || '#FF7100';
  })

  const handleChangeColor = (color: string) => {
    checkedColor.value = color;
  }

  const initColor = (color: string) => {
    if (color === '') {
      checkedColor.value = '#FF7100,#FFFFFF';
    } else {
      checkedColor.value = color;
    }
    backupColor.value = color;

    if (colorList.value.findIndex(item => item.color === color) > -1) return;

    const _color = color.split(',')[0];
    handleUpdateColorList(_color);
    customColor.value = _color;
  }

  const handleResetColorList = () => {
    colorList.value = [{
      label: i18n.t('portal.orange'),
      value: 1,
      color: '#FF7100,#FFFFFF',
    }, {
      label: i18n.t('portal.blue'),
      value: 2,
      color: '#096DD9,#FFFFFF',
    }, {
      label: i18n.t('portal.green'),
      value: 3,
      color: `${getThemeColor()},#FFFFFF`,
    }, {
      label: i18n.t('portal.customConfiguration'),
      value: 4,
      color: '#000000,#FFFFFF',
    }]
  }

  const handleUpdateColorList = (color: string | null) => {
    if (!color) return handleResetColorList();

    const newColor = {
      label: i18n.t('portal.customConfiguration'),
      value: 4,
      color: [color, '#FFFFFF'].join(','),
    }

    colorList.value.pop();
    colorList.value.push(newColor);
    handleChangeColor(newColor.color);
  }

  const handleCheckSave = (): boolean => {
    return backupColor.value === checkedColor.value
  }

  const handleBack = () => {
    if (handleCheckSave()) {
      window.history.back()
      return
    }

    MessageBox.confirm(i18n.t('portal.portalTip11'), i18n.t('common.base.toast'), {
      confirmButtonText: i18n.t('common.base.confirm'),
      cancelButtonText: i18n.t('common.base.cancel'),
      type: 'warning'
    }).then(() => {
      window.history.back()
    }).catch(() => {
      // 
    })
  }

  const handleSave = async (typeId: string, isRelease: boolean) => {
    try {
      const params = {
        typeId,
        themeColour: checkedColor.value,
        draft: isRelease ? 0 : 1
      }
      const { success } = await updateDoorThemeColour(params);
      return success;
    } catch (error) {
      console.error(error)
      return false;
    }
  }

  return {
    colorList,
    checkedColor,
    customColor,
    styleColor,
    initColor,
    handleCheckSave,
    handleChangeColor,
    handleUpdateColorList,
    handleBack,
    handleSave,
  }
}

// 自助门户字段配置和底部导航栏配置
export function usePortal(formRerf: Ref<any>) {
  
  let homeFields = ref<IPortalFields[]>([]);
  let serviceFields = ref<IPortalFields[]>([]);
  let mallFields = ref<IPortalFields[]>([]);
  let userFields = ref<IPortalFields[]>([]);
  let globalFields = ref<IPortalFields[]>([]);
  let checkedTabbarIndex = ref(PortalTabbarEnum.Home);
  
  const backup = ref<Record<string, IPortalFields[]>>({
    homeFields: [],
    serviceFields: [],
    mallFields: [],
    userFields: [],
    globalFields: [],
  })
  
  const currentFields = computed(() => {
    switch (checkedTabbarIndex.value) {
      case PortalTabbarEnum.Home:
        return homeFields.value;
      case PortalTabbarEnum.Service:
        return serviceFields.value;
      case PortalTabbarEnum.Mall:
        return mallFields.value;
      case PortalTabbarEnum.User:
        return userFields.value;
      default:
        return [];
    }
  })

  const tabbarsList = computed<ITabbarsFields[]>(() => {
    const field = globalFields.value.find(item => item.formType === 'tabbar');
    const list = (field?.setting?.list || []) as ITabbarsFields[];
    // 如果底部导航栏隐藏了当前模块，就跳到第一个显示的模块
    const tab = list.find(item => item.order === checkedTabbarIndex.value);
    if (tab?.isVisible === false) {
      checkedTabbarIndex.value = list.find(item => item.isVisible)?.order || PortalTabbarEnum.User;
    }

    return list.filter(item => {
      
      // 商城控制显示
      if (item.value == 'market') {
        return isShowLinkCShop(_versionControlMap)
      }
      
      return item
    });
  })

  const handleToggleTabbar = (index: number) => {
    if (checkedTabbarIndex.value === PortalTabbarEnum.Home) {
      let homeFieldsMessage = validateHomeFields()
      if (!isEmpty(homeFieldsMessage)) {
        checkedTabbarIndex.value = PortalTabbarEnum.Home;
        const field = homeFieldsMessage?.[0]?.field;
        field && formRerf.value.chooseField(field);
        return false;
      }
    }

    if (checkedTabbarIndex.value === PortalTabbarEnum.Service) {
      let serviceFieldsMessage = validateServiceFields()
      if (!isEmpty(serviceFieldsMessage)) {
        checkedTabbarIndex.value = PortalTabbarEnum.Service;
        const field = serviceFieldsMessage?.[0]?.field;
        field && formRerf.value.chooseField(field);
        return false;
      }
    }

    checkedTabbarIndex.value = index;
    formRerf.value.resetCurrentField();
    return true;
  };


  // 初始化各个模块的数据内容
  const initDoorTypeField = (fieldList: IPortalFields[]) => {
    const _homeFields = fieldList.filter(field => field.modular == 'homepage')
    const _serviceFields = fieldList.filter(field => field.modular == 'service')
    const _mallFields = fieldList.filter(field => field.modular == 'market')
    const _userFields = fieldList.filter(field => field.modular == 'personal')
    const _globalFields = fieldList.filter(field => field.modular == 'global')

    homeFields.value = FormUtil.initializeSetting(_homeFields);
    serviceFields.value = FormUtil.initializeSetting(_serviceFields)
    mallFields.value = FormUtil.initializeSetting(_mallFields)
    userFields.value = FormUtil.initializeSetting(_userFields)
    globalFields.value = FormUtil.initializeSetting(_globalFields)

    // let isHasUserCenterField = userFields.some(field => field.formType == 'userCenter')
    // if (isHasUserCenterField) {
    //   userFields.values = userFields
    // } else {
    //   userFields.values = [UserCenterField].concat(userFields)
    // }

    backup.value.homeFields = _.cloneDeep(homeFields.value) as any as IPortalFields[]
    backup.value.serviceFields = _.cloneDeep(serviceFields.value) as any as IPortalFields[]
    backup.value.mallFields = _.cloneDeep(mallFields.value) as any as IPortalFields[]
    backup.value.userFields = _.cloneDeep(userFields.value) as any as IPortalFields[]
    backup.value.globalFields = _.cloneDeep(globalFields.value) as any as IPortalFields[]
  }

  const updateFields = (fieldList: IPortalFields[]) => {
    if (checkedTabbarIndex.value === PortalTabbarEnum.Home) {
      homeFields.value = fieldList;
    }

    if (checkedTabbarIndex.value === PortalTabbarEnum.Service) {
      serviceFields.value = fieldList;
    }
  }
  
  const handleCheckSave = () => {
    return _.isEqual(homeFields.value, backup.value.homeFields)
      && _.isEqual(serviceFields.value, backup.value.serviceFields)
      && _.isEqual(globalFields.value, backup.value.globalFields)
  }

  const handleBack = () => {
    if (handleCheckSave()) {
      window.history.back()
      return
    }

    MessageBox.confirm(i18n.t('portal.portalTip11'), i18n.t('common.base.toast'), {
      confirmButtonText: i18n.t('common.base.confirm'),
      cancelButtonText: i18n.t('common.base.cancel'),
      type: 'warning'
    }).then(() => {
      window.history.back()
    }).catch(() => {
      // 
    })
  }

  const buildFields = (typeId: string, isClone: boolean) => {
    let _homeFields = FormUtil.toField(
      homeFields.value,
      'homepage',
      typeId,
      isClone
    );
    let _serviceFields = FormUtil.toField(
      serviceFields.value,
      'service',
      typeId,
      isClone
    );
    let _mallFields = FormUtil.toField(
      mallFields.value,
      'mall',
      typeId,
      isClone
    );
    let _userFields = FormUtil.toField(
      userFields.value,
      'personal',
      typeId,
      isClone
    );
    let _globalFields = FormUtil.toField(
      globalFields.value,
      'global',
      typeId,
      isClone
    );

    return [..._homeFields, ..._serviceFields, ..._mallFields, ..._userFields, ..._globalFields]
  };

  const validateHomeFields = () => {
    const _homeFields = homeFields.value;
    // 表单字段格式校验
    let message = FormUtil.validate(_homeFields);
    if (!FormUtil.notification(message, h)) {
      FormUtil.setFieldError(message);
      return message;
    }

    return [];
  };

  const validateServiceFields = () => {
    const _serviceFields = serviceFields.value;
    // 表单字段格式校验
    let message = FormUtil.validate(_serviceFields);
    if (!FormUtil.notification(message, h)) {
      FormUtil.setFieldError(message);
      return message;
    }

    return [];
  };

  const validateUserFieldsFields = () => {
    const _userFields = userFields.value;
    // 表单字段格式校验
    let message = FormUtil.validate(_userFields);
    if (!FormUtil.notification(message, h)) {
      FormUtil.setFieldError(message);
      return message;
    }

    return [];
  };

  const validateFields = () => {
    formRerf.value.changeSettingComponentIsValidateAll();

    let homeFieldsMessage = validateHomeFields();
    if (!isEmpty(homeFieldsMessage)) {
      checkedTabbarIndex.value = PortalTabbarEnum.Home;
      const field = homeFieldsMessage?.[0]?.field;
      field && formRerf.value.chooseField(field);
      return false;
    }

    let serviceFieldsMessage = validateServiceFields();
    if (!isEmpty(serviceFieldsMessage)) {
      checkedTabbarIndex.value = PortalTabbarEnum.Service;
      const field = serviceFieldsMessage?.[0]?.field;
      field && formRerf.value.chooseField(field);
      return false;
    }

    let userFieldsFieldsMessage = validateUserFieldsFields();
    if (!isEmpty(userFieldsFieldsMessage)) {
      checkedTabbarIndex.value = PortalTabbarEnum.User;
      const field = userFieldsFieldsMessage?.[0]?.field;
      field && formRerf.value.chooseField(field);
      return false;
    }

    return true;
  };

  const handleSave = async (isRelease: Boolean, params: any) => {
    try {
      if (isRelease) {
        // 发布
        const { success } = await updateDoorTypeFieldList(params)
        return success;
      } else {
        // 保存
        const { success, message } = await updateDoorTypeFieldListDraft(params)
        return success;
      }
    } catch (error) {
      console.error(error)
      return false;
    }
  }

  return {
    globalFields,
    tabbarsList,
    currentFields,
    checkedTabbarIndex,
    initDoorTypeField,
    updateFields,
    validateFields,
    buildFields,
    handleSave,
    handleCheckSave,
    handleBack,
    handleToggleTabbar
  }
}
